package com.jrx.anytxn.param.service.sms.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jrx.anytxn.i18n.response.TxnPage;
import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.common.uitl.BeanMapping;
import com.jrx.anytxn.common.uitl.StringUtils;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.constant.ErrorMsgConstant;
import com.jrx.anytxn.param.dto.sms.PrSmsSendingRulesTableReq;
import com.jrx.anytxn.param.dto.sms.PrSmsSendingRulesTableRes;
import com.jrx.anytxn.param.entity.PrSmsSendingRules;
import com.jrx.anytxn.param.mapper.ext.ExtPrSmsSendingRulesMapper;
import com.jrx.anytxn.param.service.sms.ISmsSendingRulesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


@Service
@CacheConfig(cacheNames = "SMS_RULES")
public class SmsSendingRulesServiceImpl implements ISmsSendingRulesService {

    private static final Logger logger = LoggerFactory.getLogger(SmsSendingRulesServiceImpl.class);

    @Resource
    private ExtPrSmsSendingRulesMapper extPrSmsSendingRulesMapper;
    @Autowired
    private ISegmentService segmentService;


    @Override
    public PrSmsSendingRulesTableRes getByTenIdIdAndRulesId(String tenantId, String rulesId) throws TxnException {
        if (StringUtils.isBlank(tenantId) || StringUtils.isBlank(rulesId)) {
            logger.error("短信发送规则ID或租户ID为空");
            throw new TxnException(TxnRespCode.NOT_EMPTY.getMsg());
        }
        PrSmsSendingRules table = extPrSmsSendingRulesMapper.selectByTenantIdAndRulesId(tenantId,rulesId);
        return BeanMapping.copy(table, PrSmsSendingRulesTableRes.class);
    }

    @Override
    public PrSmsSendingRulesTableRes addSmsSendingRules(PrSmsSendingRulesTableReq request) throws TxnException {
        //参数校验 短信模板ID 微信模板ID不能都为空
        if(StringUtils.isBlank(request.getTemplateId()) && StringUtils.isBlank(request.getWxTemplateId())){
            logger.error(TxnRespCode.NOT_EMPTY.getMsg());
            throw new TxnException(TxnRespCode.NOT_EMPTY.getMsg());
        }

        //判断短信规则是否存在
        PrSmsSendingRules table = extPrSmsSendingRulesMapper.selectByProductIdAndSmsTypeAndTempId(request.getTenantId(),request.getOrganizationId(),request.getSmsType(),request.getTemplateId(),request.getProductId(),request.getReminderCycle());
        if (table != null) {
            logger.error(TxnRespCode.DATA_EXISTS.getMsg());
            throw new TxnException(TxnRespCode.DATA_EXISTS.getMsg());
        }
        PrSmsSendingRules rulesTable = BeanMapping.copy(request, PrSmsSendingRules.class);
        try {
            rulesTable.setId(segmentService.getId(Constant.PR_SMS_SENDING_RULES));
        } catch (SegmentException e) {
            logger.error("主键生成错误",e);
            throw new TxnException(ErrorMsgConstant.ERROR_ID);
        }
        rulesTable.setRecordVersionNumber(Constant.VERSION_NUMBER);
        extPrSmsSendingRulesMapper.insertSelective(rulesTable);
        return BeanMapping.copy(rulesTable, PrSmsSendingRulesTableRes.class);
    }

    @Override
    public TxnPage<PrSmsSendingRulesTableRes> findAllPageByCondition(Integer pageNum, Integer pageSize, PrSmsSendingRules prSmsSendingRules) throws TxnException {
        Page<PrSmsSendingRulesTableRes> page = PageHelper.startPage(pageNum, pageSize, Constant.ORDER_BY_SORT);
        List<PrSmsSendingRules> tableList = extPrSmsSendingRulesMapper.selectByCondition(prSmsSendingRules);
        if (tableList.isEmpty()) {
            logger.error(TxnRespCode.NO_DATA.getMsg());
            throw new TxnBizException(TxnRespCode.NO_DATA.getMsg());
        }
        List<PrSmsSendingRulesTableRes> res = BeanMapping.copyList(tableList, PrSmsSendingRulesTableRes.class);
        return new TxnPage<>(pageNum, pageSize, page.getTotal(), res);
    }

    @Override
    public List<PrSmsSendingRulesTableRes> findAllSmsSendingRulesByTenId(String tenantId) {
        List<PrSmsSendingRules> rulesList = extPrSmsSendingRulesMapper.selectByTenantId(tenantId,null);
        return BeanMapping.copyList(rulesList, PrSmsSendingRulesTableRes.class);
    }

    @CacheEvict(key = "'smsRules_'+#request.getTenantId()+'_'+#request.getRulesId()")
    @Override
    public PrSmsSendingRulesTableRes modifySmsSendingRules(PrSmsSendingRulesTableReq request) throws TxnBizException {
        PrSmsSendingRules table = extPrSmsSendingRulesMapper.selectByTenantIdAndRulesId(request.getTenantId(),request.getRulesId());
        if (table == null) {
            logger.error(TxnRespCode.NO_DATA.getMsg());
            throw new TxnBizException(TxnRespCode.NO_DATA.getMsg());
        }
        PrSmsSendingRules newTable = BeanMapping.copy(request, PrSmsSendingRules.class);
        // 更新
        extPrSmsSendingRulesMapper.updateByTenantIdAndRulesId(newTable);
        return BeanMapping.copy(newTable, PrSmsSendingRulesTableRes.class);
    }

    @CacheEvict(key = "'smsRules_'+#tenantId+'_'+#rulesId")
    @Override
    public Boolean removeByTenantIdAndRulesId(String tenantId, String rulesId) throws TxnBizException {
        if (org.apache.commons.lang.StringUtils.isBlank(tenantId) || org.apache.commons.lang.StringUtils.isBlank(rulesId)) {
            logger.error(TxnRespCode.NOT_EMPTY.getMsg());
            throw new TxnBizException(TxnRespCode.NOT_EMPTY.getMsg());
        }
        int i = extPrSmsSendingRulesMapper.deleteByTenantIdAndRulesId(tenantId, rulesId);
        return i > 0;
    }


    @Cacheable(key = "'smsRules_'+#productId+'_'+#smsType+'_'+#sumStatus+'_'+#tenantId")
    @Override
    public PrSmsSendingRules getByProductIdAndSmsTypeAndSumStatus(String productId, String smsType, String sumStatus,String tenantId){
        return extPrSmsSendingRulesMapper.selectByProductIdAndSmsTypeAndSumStatus(productId,smsType,sumStatus,tenantId);
    }
}
